class Solution
{
public:
    vector<int> largestValues(TreeNode *root)
    {
        if (!root)
            return {};
        vector<int> ans;
        queue<TreeNode *> q;
        int num = 1;
        q.push(root);
        while (q.size())
        {
            int max_num = INT_MIN;
            while (num--)
            {
                auto tt = q.front();
                q.pop();
                max_num = max(max_num, tt->val);
                if (tt->left)
                    q.push(tt->left);
                if (tt->right)
                    q.push(tt->right);
            }
            // 插入当前层的结点最大值
            ans.push_back(max_num);
            num = q.size();
        }
        return ans;
    }
};